<template>
	<view class="searchbar u-flex u-flex-items-center" :style="{ background: bg }">
		<image src="/static/search.png" mode="widthFix" class="search-icon"></image>
		<swiper v-if="!isSearch" v-model="current" vertical autoplay circular interval="5000" class="tui-swiper">
			<swiper-item v-for="(item, index) in hotSearch" :key="index" class="tui-swiper-item" @tap="navToSearch(item.name)">
				<view class="tui-hot-item">{{ item.name }}</view>
			</swiper-item>
		</swiper>
		<template v-else>
			<input
				type="text"
				class="u-flex-sub"
				@input="inputVal"
				v-model.trim="searchkey"
				:placeholder="searchplaceholder"
				@confirm="search"
				placeholder-class="placeholder"
				confirmType="search"
			/>
			<u-icon name="close-circle-fill" color="#999" size="40" @tap="cleanKey" v-if="searchkeyword"></u-icon>
		</template>
	</view>
</template>

<script>
let reg = /([^\u0020-\u007E\u00A0-\u00BE\u2E80-\uA4CF\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFFEF\u0080-\u009F\u2000-\u201f\u2026\u2022\u20ac\r\n])|(\s)/g;
export default {
	name: 'searchbar',
	props: {
		searchplaceholder: {
			type: String,
			default: '搜索关键字'
		},
		bg: {
			type: String,
			default: '#FFFFFF'
		},
		isSearch: {
			type: Boolean,
			default: false
		},
		value: {
			type: [Number, String],
			default: 0
		}
	},
	data() {
		return {
			searchkey: '',
			hotSearch: []
		};
	},
	watch: {
		value() {
			this.searchkey = this.value;
		}
	},
	created() {
		this.searchkey = this.value;
		this.getHistory();
	},
	methods: {
		inputVal(e) {
			let val = e.detail.value;
			if (val.match(reg)) {
				val = val.replace(reg, '');
				this.$nextTick(() => {
					this.searchkey = val;
				});
			}
		},
		navToSearch(name) {
			if (!this.isSearch) {
				uni.navigateTo({
					url: '/pages/search/search?placeholdertext=' + name
				});
			}
		},
		cleanKey() {
			this.searchkey = '';
		},
		search() {
			this.$emit('search', this.searchkey);
		},
		/* 获取查询历史 */
		getHistory() {
			this.$postAction(this.$api.searchRecord, null, {
				custom: {
					ShowLoading: false
				}
			}).then(da => {
				this.hotSearch = [...da.data.guess_like];
			});
		}
	}
};
</script>

<style lang="scss">
.searchbar {
	height: 64upx;
	background: rgba(255, 255, 255, 0.8);
	border-radius: 32px;
	padding-right: 8upx;
	padding-left: 32upx;
	font-weight: normal;
	input {
		font-size: 24upx;
		color: #666;
	}
	.search-icon {
		width: 28upx;
		height: 28upx;
		display: block;
		margin-right: 13upx;
	}
	.placeholder {
		color: #999;
	}
	.tui-swiper {
		font-size: 26rpx;
		height: 60rpx;
		flex: 1;
		padding-left: 12rpx;
	}

	.tui-swiper-item {
		display: flex;
		align-items: center;
	}
	.tui-hot-item {
		line-height: 26rpx;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
		color: #999;
	}
}
</style>
